package com.up.vms.domain.vm.service;

import com.up.vms.domain.module.CategoryDTO;
import com.up.vms.domain.vm.entity.Category;
import com.up.vms.domain.vm.enums.CategoryStatus;
import com.up.vms.domain.vm.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    public Page<Category> findAllByBannerName(CategoryDTO categoryDTO) {
        Sort sort = new Sort(Sort.Direction.DESC, "sorting");
        Pageable pageable = PageRequest.of(categoryDTO.getPage(), categoryDTO.getSize(), sort);

        return categoryRepository.findAllByCategoryLike("%" + categoryDTO.getCategory() + "%", pageable);
    }

    public Page<Category> findAllByStatus(CategoryDTO bannerDTO) {
        Sort sort = new Sort(Sort.Direction.DESC, "sorting");
        Pageable pageable = PageRequest.of(bannerDTO.getPage(), bannerDTO.getSize(), sort);

        return categoryRepository.findAllByStatus(CategoryStatus.AVAILABLE.code, pageable);
    }

    public Page<Category> findAllByPageable(CategoryDTO bannerDTO) {
        Sort sort = new Sort(Sort.Direction.DESC, "sorting");
        Pageable pageable = PageRequest.of(bannerDTO.getPage(), bannerDTO.getSize(), sort);

        return categoryRepository.findAll(pageable);
    }


    public Category findCategoryById(Long categoryId) {

        Optional<Category> optional = categoryRepository.findById(categoryId);

        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    public Category save(Category category) {
        Category newCategory = categoryRepository.save(category);
        return newCategory;
    }

    public void delete(Category category) {
        categoryRepository.delete(category);
    }
}
